package com.kx.forum.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.kx.base.dto.file.ImgDTO;
import com.kx.base.result.R;
import com.kx.forum.client.FileClient;
import com.kx.forum.mapper.ForumMapper;
import com.kx.forum.pojo.Forum;
import com.kx.forum.service.ForumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Sun
 * @date 2021/8/10 21:00
 */
@Service
public class ForumServiceImpl implements ForumService {
    @Autowired
    private FileClient fileClient;

    @Resource
    private ForumMapper forumMapper;

    @Override
    public int createForum(Long userId, String title, String content, List<String> images, Integer imageCount, String video) {
        List<String> imageUrls = new ArrayList<>();
        if (images != null && images.size() > 0) {
            for (int i = 0; i < imageCount; i++) {
                //拿到每个图片的base64，将图片上传到文件服务器
                String image = images.get(i);
                ImgDTO imgDTO = new ImgDTO();
                imgDTO.setBase64(image);
                R r = fileClient.uploadImage(imgDTO);
                //获取文件服务器返回的url
                if (r.isOK()) {
                    JSONObject jsonObject = new JSONObject((Map<String, Object>) r.getResult());
                    String url = (String) jsonObject.get("url");
                    imageUrls.add(url);
                }
            }
        }
        String videoUrl = null;
        if (video != null) {
            //将视频上传到文件服务器
            ImgDTO imgDTO = new ImgDTO();
            imgDTO.setBase64(video);
            R r = fileClient.uploadImage(imgDTO);
            if (r.isOK()) {
                JSONObject jsonObject = new JSONObject((Map<String, Object>) r.getResult());
                videoUrl = (String) jsonObject.get("url");
            }
        }
        Forum forum = new Forum();
        forum.setTitle(title);
        forum.setContent(content);
        forum.setImage(JSONObject.toJSONString(imageUrls));
        forum.setImageCount(imageCount);
        forum.setVideo(videoUrl);
        forum.setUid(userId);
        return forumMapper.insertSelective(forum);
    }
}
